﻿using System;
using System.Drawing;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media.Imaging;
using SSG.Tools;

namespace SSG.View
{
    /// <summary>
    /// Utilities for the tree view
    /// </summary>
    public static class TreeViewUtil
    {
        /// <summary>
        /// Create a tree view item
        /// </summary>
        /// <param name="name"></param>
        /// <param name="icon"></param>
        /// <returns></returns>
        public static TreeViewItem GetTreeViewItem(string name, Bitmap icon = null)
        {
            // http://blogs.msdn.com/b/sergeim/archive/2008/03/26/wpf-treeview-with-icons.aspx
            name = TreeViewUtil.FixItenName(name);
            StackPanel panel = new StackPanel {Orientation = Orientation.Horizontal, Background = System.Windows.Media.Brushes.Transparent};
            BitmapImage bi = icon.GetBitmapImage();
            System.Windows.Controls.Image controlImage = new System.Windows.Controls.Image {Source = bi};
            panel.Children.Add(controlImage);
            panel.Children.Add(new TextBlock(new Run(name)));
            TreeViewItem tvi = new TreeViewItem {Header = panel, Name = name};
            return tvi;
        }

        /// <summary>
        /// Rename tree view
        /// </summary>
        /// <param name="name"></param>
        /// <param name="treeViewItem"></param>
        public static void RenameItem(string name, TreeViewItem treeViewItem)
        {
            if (treeViewItem == null) throw new ArgumentNullException("treeViewItem");
            name = TreeViewUtil.FixItenName(name);
            StackPanel panel = treeViewItem.Header as StackPanel;
            if (panel == null) throw new InvalidOperationException("No stack panel");
            panel.Children.RemoveAt(1);
            panel.Children.Add(new TextBlock(new Run(name)));
        }

        /// <summary>
        /// Item name
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private static string FixItenName(string name)
        {
            if (String.IsNullOrEmpty(name)) throw new ArgumentNullException("name");
            name = name.Replace(' ', '_');
            return name;
        }

    }
}